<?php

namespace App\Admin\Controllers;

use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use App\Support\Config;
use App\Models\UserSwitch;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\URL;

class UsersController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        // dd(\Request::server('HTTP_HOST'));
        return $content
            ->header('用户列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show(User $user, Content $content)
    {
        return $content
            ->header('用户详情')
            ->body(view('admin.users.show', ['user' => $user]));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('用户修改')
            ->body($this->form()->edit($id));
    }
    

    /**
     * 创建用户
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('用户创建')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new User);
        $grid->paginate(15);
        $grid->id('ID');
        $grid->name('用户名');
        $grid->vrt('vrt 值');
        $grid->total_vrt('vrt 总计');
        $grid->vrts('VRTS 值');
        $grid->yec('YEC 值');
        $grid->eth('ETH 值');
        $grid->status('用户状态')->display(function ($value) {
            return User::$stautsMap[$value];
        });
        $grid->column('userSwitch.vrts_accounts_status', 'VRTS转账')->display(function ($value) {
            return $value?'<a href="/admin/users/vrtsstatus/' . $this->id . '" class="btn btn-primary">' . UserSwitch::$vrtsStautsMap[$value] . '</a>':'<a href="/admin/users/vrtsstatus/' . $this->id . '" class="btn btn-danger">' . UserSwitch::$vrtsStautsMap[$value] . '</a>';
        });
        $grid->column('userSwitch.static_status', '静态释放状态')->display(function ($value) {
            return $value?'<a href="/admin/users/staticstatus/' . $this->id . '" class="btn btn-primary">' . UserSwitch::$staticStautsMap[$value] . '</a>':'<a href="/admin/users/staticstatus/' . $this->id . '" class="btn btn-danger">' . UserSwitch::$staticStautsMap[$value] . '</a>';
        });
        $grid->column('userSwitch.dynamic_status', '动态释放状态')->display(function ($value) {
            return $value?'<a href="/admin/users/dynamicstatus/' . $this->id . '" class="btn btn-primary">' . UserSwitch::$dynamicStautsMap[$value] . '</a>':'<a href="/admin/users/dynamicstatus/' . $this->id . '" class="btn btn-danger">' . UserSwitch::$dynamicStautsMap[$value] . '</a>';
        });
        $grid->created_at('注册时间');
        $grid->tools(function ($tools) {
            // 禁用批量删除按钮
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });
        //禁用导出
        $grid->disableExport();
        //禁用行选择checkbox
        $grid->disableRowSelector();
        $grid->filter(function ($filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            // 在这里添加字段过滤器
            $filter->like('name', '用户名');
            $filter->equal('status', '激活状态')->radio(User::$stautsMap);
            $filter->equal('userSwitch.vrts_accounts_status', 'VRTS转账是否开启')->radio(UserSwitch::$vrtsStautsMap);
            $filter->equal('userSwitch.static_status', '静态释放是否开启')->radio(UserSwitch::$staticStautsMap);
            $filter->equal('userSwitch.dynamic_status', '动态释放是否开启')->radio(UserSwitch::$dynamicStautsMap);
        });
        
        return $grid;
    }
    
    /**
     * VRTS 释放 是否关闭按钮
     */
    public function vrtsAccountsStatus($id)
    {
        $user = User::find($id)->userSwitch;
        $user->vrts_accounts_status==1?$user->vrts_accounts_status = 0:$user->vrts_accounts_status = 1;
        $user->save();
        return redirect('admin/users');
    }
    /**
     * 静态释放是否关闭
     */
    public function staticStatus($id)
    {
        $user = User::find($id)->userSwitch;
        $user->static_status==1?$user->static_status = 0:$user->static_status = 1;
        $user->save();
        return redirect('admin/users');
    }
    public function dynamicStatus($id)
    {
        $user = User::find($id)->userSwitch;
        $user->dynamic_status==1?$user->dynamic_status = 0:$user->dynamic_status = 1;
        $user->save();
        return redirect('admin/users');
    }
    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new User);
        $form->row(function ($row) use ($form) {
            $row->width(3)->text('name', '用户名')->rules(function ($form) {
                if ($id = $form->model()->id) {
                    return 'required|unique:users,name,' . $id . ',id';
                } else {
                    return 'required|unique:users';
                }
            });
            $row->width(3)->text('password', '登录密码')->rules(function ($form) {
                if ($id = $form->model()->id) {
                    return 'required|min:6|max:25' . $id . ',id';
                } else {
                    return 'required|min:6|max:25';
                }
            });
            
            $row->width(3)->text('pay_passwd', '支付密码')->rules('nullable|regex:/^\d+$/|min:6', [
                'regex' => '支付密码必须全部为数字',
                'min'   => '支付密码不能少于6个字符',
                ]);
            if (!request()->route()->parameters()) {
                $row->width(3)->text('invitation_code', '邀请码')->default(User::getInvitationCode())->readOnly();
            };

            $row->width(6)->radio('status', '用户状态')->options(User::$stautsMap);
            if (!request()->route()->parameters()) {
                $row->width(6)->text('mnemonic_word', '助记词')->readOnly()->value(function () {
                    return $this->getWalletAddressAndMnemonicWord()[1];
                })->rules(function ($form) {
                    if ($id = $form->model()->id) {
                        return 'required|unique:users,mnemonic_word,' . $id . ',id';
                    } else {
                        return 'required|unique:users';
                    }
                });
                $script = <<<SCRIPT
        $('button[type=submit]').on('click',function(e){
            event.preventDefault();
            swal({
                title: '请妥善保存好助记词!',
                text: '遗失后不能恢复!',
                type: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: '确认提交',
                cancelButtonText: "取消",
            }).then(function (isConfirm) {
                if (isConfirm.value == true ){
                     $("form").submit();
                }else{
                    event.preventDefault();
                    return false;
                }
            }).catch(swal.noop);
        });
SCRIPT;
                Admin::script($script);
            }

            $row->width(4)->decimal('vrt', 'Vrt')->default(0.00000000);
            $row->width(4)->decimal('total_vrt', 'VRT 总计')->default(0.00000000);
            $row->width(4)->decimal('vrts', 'Vrts')->default(0.00000000);
            $row->width(4)->decimal('yec', 'Yec')->default(0.00000000);
            $row->width(4)->decimal('eth', 'Eth')->default(0.00000000);
            $row->width(8)->decimal('parent_id', '推荐人ID');
        }, $form);
        
        
        
        $form->saving(function (Form $form) {
            if (!$form->model()->id) {
                $form->invitation_code = $form->invitation_code;
            }
        });
        
        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();
        });
        $form->tools(function (Form\Tools $tools) {
            // 去掉`查看`按钮
            $tools->disableView();
        });
        return $form;
    }

    /**
     * 获取用户关系数据
     */
    public function getUserRelations($id)
    {
        $data = User::with('children')->find($id)->toArray();
        return $data;
    }

    /**
     * 整理所有用户数据
     * @param $tree 当前用户下所有层级数据
     * @param int $pid 父级ID
     * @return array
     */
    public function getTree($users, $pid='')
    {
        $tree = [];
        foreach ($users as $user) {
            if ($user['parent_id'] == $pid) {
                $tree[] = $user;
                $tree = array_merge($tree, $this->getTree($users, $user['user$user_id']));
            }
        }
        return $tree;
    }

    /**
     * 获取助记词
     * @return array
     */
    private function getWalletAddressAndMnemonicWord()
    {
        $client = get_eth_client();
        $res = $client->post('/newAccount');
        $data = json_decode($res->getBody(), true)['data'];
        $walletAddress = $data['address'];
        $mnemonics = explode(' ', $data['mnemonic']);
        $mnemonicWord = implode(' ', array_slice($mnemonics, 0, 9));

        return [$walletAddress, $mnemonicWord];
    }
}
